import {Component, OnInit} from '@angular/core';
import {ReportService} from "../report.service";
import {environment} from "../../../environments/environment"
import {StorageService} from "../../services/storage.service";
import {ActivatedRoute, Router} from "@angular/router";
import {MessageService} from "primeng/components/common/messageservice";
import {ConfirmationService} from "primeng/primeng";
import {BasePage} from "../../base.page";
@Component({
  selector: 'app-report-view',
  templateUrl: './report-view.component.html',
  styleUrls: ['./report-view.component.scss']
})
export class ReportViewComponent extends BasePage implements OnInit {
  dataSource;
  totalRecords;
  cols;
  showViewDetailMask :boolean =false;//查看详情
  bar = {};//柱状图
  pie = {};//饼状图
  report = [];//报障处理总览
  reportView = [];//报障总览
  reportName = [];
  reportCount = [];
  reportViewName = [];//报障总览名称
  reportViewCount = [];//报障总览内容
  historyReportOrder = [];//历史报障单
  display: boolean = false; //模态框默认隐藏
  showReportTreatment: boolean = false;//报障总览处理
  currentHistoryReport;

  constructor(
    private reportService: ReportService,
    private storageService:StorageService,
    private route:ActivatedRoute,
    private router: Router,
    public confirmationService: ConfirmationService,
    public messageService:MessageService,
  ) {
    super(confirmationService,messageService)

  }

  ngOnInit() {
    this.cols = [
      // {field: 'cid', header: '单号'},
      {field: 'fault_type', header: '故障所属'},
      {field: 'people', header: '报障人'},
      {field: 'time', header: '报障时间'},
      {field: 'location', header: '故障位置'},
      {field: 'status', header: '状态'},
      {field: 'handle_people', header: '处理人'},
      {field: 'handle_datetime', header: '完成时间'},
    ];
   this.queryReportView();
  }
  //查看详情
  showReport(report){
    this.currentHistoryReport = report;
    this.showViewDetailMask = !this.showViewDetailMask;
  }
  closeViewDetail(bool){
    this.showViewDetailMask = bool;
  }
  onOperate(report) {
    this.currentHistoryReport = report;
    this.showViewDetailMask = !this.showViewDetailMask;
  }
  //故障处理model
  showReportTreatmentMask(report){
    this.storageService.setReportId('reportid',report.id);
    this.currentHistoryReport = report;
    this.showReportTreatment = !this.showReportTreatment;
  }
  closeReportTreamentMask(bool){
    this.showReportTreatment = bool;
  }
  loadCarsLazy(event) {
    setTimeout(() => {
      if(this.dataSource) {
        this.historyReportOrder = this.dataSource.slice(event.first, (event.first + event.rows));
      }
    }, 250);
  }
  updateOption(current){
    let cid = current['cid'];
    this.router.navigate(['../review'],{queryParams:{cid:cid,state:'update',title:'编辑'},relativeTo:this.route})
  }
  updatehistoryReportModel(handle_content){
    let reportId = parseInt(this.storageService.getReportId('reportid'));
    this.queryReportView();
    for(let i=0;i<this.dataSource.length;i++){
      if(this.dataSource[i]['id'] === reportId){
        this.dataSource[i]['showHandleButton'] = false;
        this.dataSource[i]['status'] = '已处理';
        this.dataSource[i]['handle_content'] = handle_content;
      }
    }
  }
  deleteReport(current){
    let cid = current['cid'];
    //请求成功后删除本地数据
    this.confirm('确认删除吗?',()=>{this.deleteoption(cid)});
  }
  deleteoption(cid){
    this.reportService.deleteReport(cid).subscribe(()=>{
      this.queryReportView();
      this.alert('删除成功')
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===0||JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，请联系管理员或稍后重试'
      }else{
        message = err
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  }
  queryReportView (){
    this.reportService.getReportView().subscribe((data) => {
      //1.将获取的数据保存到变量report中;
      //2.遍历report数组
      this.report = data.handle_count;
      if(!this.report){
        this.report = [];
      }
      for(let i = 0;i<this.report.length;i++){
        this.reportName.push(this.report[i].name);
        this.reportCount.push(this.report[i].count);
      }
      //  报障总览
      this.reportView = data.type_count;
      if(!this.reportView){
        this.reportView = [];
      }
      for(let i = 0;i<this.reportView.length;i++){
        this.reportViewName.push(this.reportView[i].name);
        this.reportViewCount.push(this.reportView[i].count);
      }
      this.bar = {
        title: {
          subtext: '',
          x: 'center'
        },
        color: ['#3398DB'],
        tooltip: {
          trigger: 'axis',
          axisPointer: {            // 坐标轴指示器，坐标轴触发有效
            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: ""
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: [
          {
            type: 'category',
            data: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'],
            // data: this.reportName,
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '数量',
            type: 'bar',
            barWidth: '60%',
            data: [10, 52, 200, 334, 390, 330, 220, 1000, 500, 444, 999, 11]
            // data: this.reportCount
          }
        ]
      }
      this.pie = {
        theme: '',
        event: [
          {
            type: "click",
            cb: function (res) {
              console.log(res);
            }
          }
        ],
        title: {
          text: '',
          subtext: '',
          x: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['深圳', '北京', '广州', '上海', '长沙']
          // data: this.reportViewName
        },
        series: [{
          name: '访问来源',
          type: 'pie',
          startAngle: -180,
          radius: '55%',
          center: ['50%', '60%'],
          data: this.reportService.formatPieData(this.reportView),
          itemStyle: {
            emphasis: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      //查询今日报障
      this.dataSource = data.list;
      if(!this.dataSource){
        this.dataSource = [];
      }
      for(let i =0 ;i<this.dataSource.length;i++){
        let devices = this.dataSource[i]['devices'] ? this.dataSource[i]['devices'] : [];
        // let devices = this.dataSource[i]['devices'];
        this.dataSource[i]['showdevices'] = [];
        for(let j =0;j<devices.length;j++){
          let temp = devices[j]['ano'];
          this.dataSource[i]['showdevices'].push(temp)
        }
        this.dataSource[i]['showdevices'].join(";")
      }
      this.totalRecords = this.dataSource.length;
      this.historyReportOrder = this.dataSource.slice(0, 10);

    },(err: Error) =>{

    });
  }
}
